package com.frogs.ucenter.controller;

import java.io.FileOutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.ucenter.entity.UserRechargeConsumeRecord;
import com.frogs.ucenter.entity.UserRechargeConsumeRecordWithUser;
import com.frogs.ucenter.service.UserRechargeConsumeRecordService;

@Controller
@RequestMapping("admin/user/rechargeConsumeRecord")
public class UserRechargeConsumeRecordController extends BaseController3 {
    private static final String ROOT_VIEW = "admin/userRechargeConsumeRecord";

    private static final String HOME_VIEW = "admin/userRechargeConsumeRecord/home";

    private static final String EDIT_VIEW = "admin/userRechargeConsumeRecord/edit";

    private static final String EXPORT_EXCEL = "/export";
    
    @Autowired
    private UserRechargeConsumeRecordService userRechargeConsumeRecordService;

    @RequestMapping()
    public String listUserRechargeConsumeRecord(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        if(model.containsKey("eqEmail")) {
    	    model.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        
        if(model.containsKey("eqPhone")) {
    	    model.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        model.put("orderByClause", "consume_time desc");
        getPageList( model );
        return HOME_VIEW;
    }

    @RequestMapping(EDIT)
    public String createUserRechargeConsumeRecord(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.put( "model",userRechargeConsumeRecordService.getById( id ) ); 
        }
        return EDIT_VIEW;
    }

    @RequestMapping(ADD)
    public String saveUserRechargeConsumeRecord(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserRechargeConsumeRecord userRechargeConsumeRecord) {
        setRequestModelMap(request, model, false);
        DWZResponse.Builder builder;
        try {
            userRechargeConsumeRecordService.insert( userRechargeConsumeRecord ); 
            builder = DWZResponse.getSucessBuilder("新增成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("新增失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        return null;
    }

    @RequestMapping(SHOW)
    public String showUserRechargeConsumeRecord(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.addAttribute( userRechargeConsumeRecordService.getById( id ) ); 
        }
        setRequestModelMap(request, model);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateUserRechargeConsumeRecord(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserRechargeConsumeRecord userRechargeConsumeRecordNew) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            DWZResponse.Builder builder;
            try {
                UserRechargeConsumeRecord userRechargeConsumeRecord = userRechargeConsumeRecordService.getById( id ); 
                PropertyUtils.copyProperties(userRechargeConsumeRecord, userRechargeConsumeRecordNew);
                userRechargeConsumeRecordService.update( userRechargeConsumeRecord ); 
                model.clear();
                builder = DWZResponse.getSucessBuilder("更新成功");
            } catch (Exception e) {
                builder = DWZResponse.getFailBuilder("更新失败" + e.getMessage());
            }
            RenderUtil.renderHtml(builder.build().toString(), response);
        }
        return null;
    }

    @RequestMapping(DELETE)
    public String deleteUserRechargeConsumeRecord(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            userRechargeConsumeRecordService.delete( model ); 
            builder = DWZResponse.getSucessBuilder("删除信息成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("删除信息失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    private PageList<UserRechargeConsumeRecordWithUser> getPageList(ModelMap model) {
        PageList<UserRechargeConsumeRecordWithUser> userRechargeConsumeRecordList = userRechargeConsumeRecordService.listRecharge( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        model.put("userRechargeConsumeRecordList",userRechargeConsumeRecordList);
        model.put("pageTurn",userRechargeConsumeRecordList.getPageTurn());
        return userRechargeConsumeRecordList;
    }
    
    private List<UserRechargeConsumeRecordWithUser> getList(ModelMap model) {
        PageList<UserRechargeConsumeRecordWithUser> userRechargeConsumeRecordList = userRechargeConsumeRecordService.listRecharge( model, 1, 100000 ); 
        return userRechargeConsumeRecordList;
    }
    
    @RequestMapping(EXPORT_EXCEL)
    public ModelMap exportExcel(HttpServletRequest request, ModelMap model) {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model, true);
        if(model.containsKey("eqEmail")) {
    	    model.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        
        if(model.containsKey("eqPhone")) {
    	    model.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        model.put("orderByClause", "consume_time desc");
        
        List<UserRechargeConsumeRecordWithUser> exportObjs = getList(model);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        createHead(sheet);
        String name = "用户余额消费记录";
        int index = 1 ;
        for(UserRechargeConsumeRecordWithUser obj : exportObjs){
        	exportWrite(sheet, obj, index);
        	index++;
            if(index % 100 == 0){
                try{
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        
        try{
            String path = request.getSession().getServletContext().getRealPath("/");
            String fileName = "/export/" + name + ".xls";
            FileOutputStream fileOut = new FileOutputStream(path+fileName);
            wb.write(fileOut);
            fileOut.close();
            model.put("fileName", fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return model;
    }
    
    public void exportWrite(HSSFSheet sheet,UserRechargeConsumeRecordWithUser obj,int rowIndex){
        HSSFRow row = sheet.createRow(rowIndex);
        row.createCell(0).setCellValue(obj.getAccountName());
        row.createCell(1).setCellValue(obj.getPhone());
        row.createCell(2).setCellValue(obj.getEmail());
        row.createCell(3).setCellValue(obj.getConsumeMoney().toString());
        row.createCell(4).setCellValue(obj.getConsumeContent());
        row.createCell(5).setCellValue(obj.getOrderId());
        row.createCell(6).setCellValue(DateUtil.formatDate(obj.getConsumeTime(), "yyyy-MM-dd HH:mm:ss"));
    }
    
    public void createHead(HSSFSheet sheet){
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("手机号码");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("消费金额");
        row.createCell(4).setCellValue("消费内容");
        row.createCell(5).setCellValue("订单号");
        row.createCell(6).setCellValue("消费时间");
    }
}